package com.boot2.core.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 破解防盗链
* @author  zhangweilin  
* @date 2017年5月11日 下午7:35:54
* @version V1.0  
* @Description
 */
@WebServlet(name = "ImageServlet", urlPatterns = { "/img" }, loadOnStartup = 1)
public class ImageServlet extends HttpServlet
{
    /**
     * 
     */
    private static final long serialVersionUID = -3406232829922791480L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            OutputStream os = response.getOutputStream();
            String picPath = request.getParameter("url");
            // 建立请求链接
            URLConnection u = new URL(picPath).openConnection();
            InputStream in = u.getInputStream();
            if (null != in)
            {
                int len;
                byte[] b = new byte[1024];
                while ((len = in.read(b)) != -1)
                {
                    os.write(b, 0, len);
                }
                os.flush();
                in.close();
            }
            os.close();
//            Writer writer = response.getWriter();
//            response.getWriter().flush();
//            JspFactory fac = JspFactory.getDefaultFactory();
//            PageContext pageContext = fac.getPageContext(this, request, response, null, false, JspWriter.DEFAULT_BUFFER, true);
//
//            // 将图片内容重写到页面
//            writer = pageContext.pushBody();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        this.doGet(request, response);
    }
}
